const app = getApp();
let recordingTimeInterval;
let scopeRecordInterval;
let recorderManager;
Page({
	
	/**
	 * 页面的初始数据
	 */
	data: {
		settleOrderMsg: true,
		recordMsg: false,
		recordingTime: 0,//录音计时
		recordingTime_text: '00:00:00',
		cdnUrl: '',
		radioItems: [
			{ name: '线上支付', value: '1' },
			{ name: '线下支付', value: '0' }
		],
		/* 自定义导航栏参数 */
		loading: false,
		color: '#000',
		background: '#FFFFFF',
		show: true,
		animated: false,
		title: '回收结算',
		back: true,
		
		/* 订单详情 */
		form: {
			id: 0,
			pay_type: '', //默认线下支付
			recordfile: '',//录音文件路径
			realGoodsInfo: [
				{
					recovery_category_name: '请选择',
					recovery_category_id: 0,
					weight: '',
					unit: '',
					price: '',//骑手输入单价
					total_price: ''//该商品的总价
				}
			]
		},
		estimate_price: 0,//定义所有回收物品的金额
		recordFile: {
			duration: 0,
			fileSize: 0,
			tempFilePath: ""
		},//保存录音临时文件
		
		orderDetail: {},
		/* 物品分类数据 */
		cregion: [ '', '' ],
		cvalueRegion: [ 0, 0 ],
		cdistrict: [],
		cmultiArray: [],
		cmultiIndex: [ 0, 0 ]
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		wx.removeStorageSync('recordfile');
		wx.removeStorageSync('isRecording');
		wx.removeStorageSync('recordingTime');
		var that = this;
		recorderManager = wx.getRecorderManager();
		if ( options.hasOwnProperty('id')==false ) {
			app.error('订单参数错误');
			setTimeout(function () {
				wx.navigateBack({});
			}, 1500)
		} else {
			that.orderDetail(options.id);
		}
		that.setData({
			cdnUrl: app.cdnUrl
		});
		if ( wx.getStorageSync('isRecording')==true ) {
			that.setData({
				recordMsg: true
			})
			/* 录音倒计时继续 */
			clearTimeout(recordingTimeInterval);
			that.count_down(wx.getStorageSync('recordingTime')*1);
		}
		/*监听录音错误事件*/
		recorderManager.onError(function (res) {
			console.log(res);
//			app.error(res.errMsg);
		})
		/*监听录音设备停止事件*/
		recorderManager.onStop(function (res) {
			console.log(res);
			/* 	duration: 7660
					fileSize: 46290
					tempFilePath: "wxfile://tmp_8a7e905fa0a22f51dd6017ad075a2e0468f1b691ce8ca9d6.m4a"
			*/
//					 wx.setStorageSync('recordfile', res);
			wx.setStorageSync('isRecording', false);
			wx.setStorageSync('temp_directory', res);
			//上传录音设备
//			that.uploadRecord(res);
		})
	},
	/* 录音 */
	startRecord: function () {
		var that = this;
		that.setData({
			recordMsg: true
		});
		wx.getSetting({
			success (res) {
				if ( !res.authSetting['scope.record'] ) {
					wx.authorize({
						scope: 'scope.record',
						success () {
							// 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
							recorderManager.start({
								duration: 600000,
								format: 'mp3'
							});
							that.setData({
								isRecording: true
							})
							wx.setStorageSync('isRecording', true);
							/* 录音计时 */
							that.count_down(that.data.recordingTime);
						},
						fail () {
							wx.showModal({
								title: '请授权录音',
								content: '回收过程需要进行录音',
								confirmColor: '#00cd85',
								cancelColor: '#333',
								success: function (tip) {
									if ( tip.confirm ) {
										wx.openSetting({
											success: function (data) {
												if ( data.authSetting["scope.record"]===true ) {
													recorderManager.start({
														duration: 600000,
														format: 'mp3'
													});
													that.setData({
														isRecording: true
													})
													wx.setStorageSync('isRecording', true)
													/* 录音计时 */
													that.count_down(that.data.recordingTime);
												} else {
													that.scopeRecord();
												}
											}
										})
									} else {
										that.scopeRecord();
									}
								}
							})
						}
					})
				} else {
					// recorderManager = wx.getRecorderManager();
					recorderManager.start({
						duration: 600000,
						format: 'mp3'
					});
					wx.setStorageSync('isRecording', true)
					/* 录音计时 */
					that.count_down(that.data.recordingTime);
				}
			}
		})
	},
	scopeRecord: function () {
		var that = this;
		clearTimeout(scopeRecordInterval);
		wx.showModal({
			title: '请授权录音',
			content: '回收过程需要进行录音',
			confirmColor: '#00cd85',
			cancelColor: '#333',
			success: function (tip) {
				if ( tip.confirm ) {
					wx.openSetting({
						success: function (data) {
							if ( data.authSetting["scope.record"]===true ) {
								// 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
								// recorderManager = wx.getRecorderManager();
								recorderManager.start({
									duration: 600000,
									format: 'mp3'
								});
								that.setData({
									isRecording: true
								})
								wx.setStorageSync('isRecording', true)
								/* 录音计时 */
								that.count_down(that.data.recordingTime);
							} else {
								that.scopeRecord();
							}
						}
					})
				} else {
					scopeRecordInterval = setTimeout(function () {
						that.scopeRecord();
					}, 1)
				}
			}
		})
	},
	count_down: function (remaintime) {
		var that = this;
		var expireMs = remaintime;
//			console.log(that.data.recordingTime_text);
		that.setData({
			recordingTime_text: that.date_format(expireMs)
		});
		wx.setStorageSync('recordingTime', expireMs + 1);
		recordingTimeInterval = setTimeout(function () {
			expireMs = expireMs + 1;
			if ( expireMs>=60000 ) clearInterval(recordingTimeInterval);
			that.count_down(expireMs);
		}, 1000)
	},
	/* 格式化倒计时 */
	date_format: function (seconds) {
		var that = this;
		// var day = that.fill_zero_prefix(Math.floor(seconds / 86400)) //天
		var folur = that.fill_zero_prefix(Math.floor((seconds%86400)/3600))//小时
		var min = that.fill_zero_prefix(Math.floor((seconds%3600)/60));// 分钟位
		var sec = that.fill_zero_prefix(seconds%60); // equal to => var sec = second % 60;// 秒位
		return folur + ':' + min + ':' + sec;
	},
	fill_zero_prefix: function (num) {
		return num<10 ?"0" + num:num
	},
	/* 获取订单详情 */
	orderDetail: function (id) {
		var that = this;
		app.request('/api/timetable.user/orderDetail', {
			id: id,
			is_settle: true
		}, function (data, ret) {
			that.setData({
				orderDetail: data,
				['form.id']: data.id,
				['form.realGoodsInfo']: data.goodsList
			});
		}, function (data, ret) {
			app.error(ret.msg);
			setTimeout(function () {
				wx.navigateBack({});
			}, 1500)
		});
	},
	
	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function (e) {
		// 获取当前小程序的页面栈
		var that = this;
		if ( app.globalData.userInfo ) {
			that.setData({
				userInfo: app.globalData.userInfo
			});
		} else {
			setTimeout(function () {
				if ( app.globalData.userInfo ) {
					that.onShow();
				} else {
					let pages = getCurrentPages();
					let currentPage = pages[pages.length - 1].route;
					if ( pages.length>1 ) {
						app.check(function (ret) {
						}, '/' + currentPage);
					} else {
						app.check(function (ret) {
						}, '/page/index/index');
					}
				}
			}, 500)
		}
		app.request('/addons/cms/wxapp.recovery/select', {}, function (data, ret) {//获取物品信息
			that.setData({
				cdistrict: data
			});
			that.categoryInitialize();//分类选择数据
		}, function (data, ret) {
			app.error(ret.msg);
		});
	},
	/* 回收物品分类选择 */
	categoryInitialize: function () {
		let that = this, top = [], second = [];
		if ( that.data.cdistrict.length ) {
			let topChildren = that.data.cdistrict[0].c || [];
			that.data.cdistrict.forEach(function (item) {
				top.push(item.n);
			});
			topChildren.forEach(function (item) {
				second.push(item.n);
			});
			that.setData({
				cmultiArray: [ top, second ]
			});
		}
	},
	bindCategoryChange: function (e) {
		var that = this;
		let cmultiIndex = that.data.cmultiIndex, top = that.data.cdistrict[cmultiIndex[0]] || { c: [] },
			second = top.c[cmultiIndex[1]] || { v: 0 }, cmultiArray = that.data.cmultiArray, value = e.detail.value;
		var offset = e.currentTarget.dataset.index;
		var realGoodsInfo = that.data.form.realGoodsInfo;
		var goods = [];
		realGoodsInfo.forEach(function (item, index) {
			if ( offset==index ) {
				var info = {
					recovery_category_name: cmultiArray[1][value[1]]=="" ?cmultiArray[0][value[0]]:cmultiArray[0][value[0]] + "," + cmultiArray[1][value[1]],
					recovery_category_id: second.v,
					weight: item.weight,
					unit: second.u,
					price: '',//骑手输入单价
					total_price: ''//该商品的总价
				};
				goods.push(info);
			} else {
				goods.push(item);
			}
		})
		console.log(goods);
		that.setData({
			['form.realGoodsInfo']: goods,
			cvalueRegion: [ 0, 0 ]
		})
		this.categoryInitialize();
	},
	bindCategoryColumnChange: function (e) {
		let that = this, column = e.detail.column, value = e.detail.value,
			currentCity = this.data.cdistrict[value] || { c: [] }, cmultiArray = that.data.cmultiArray,
			cmultiIndex = that.data.cmultiIndex;
		cmultiIndex[column] = value;
		switch ( column ) {
			case 0:
				let areaList = currentCity.c[0] || { c: [] };
				cmultiArray[1] = currentCity.c.map((item)=>{
					return item.n;
				});
				break;
			case 1:
				break;
			case 2:
				
				break;
		}
		this.setData({ cmultiArray: cmultiArray, cmultiIndex: cmultiIndex });
	},
	weightChange: function (e) {
		var that = this;
		var offset = e.currentTarget.dataset.index;
		var realGoodsInfo = that.data.form.realGoodsInfo;
		var goods = [];
		var weight = e.detail.value;
		var estimate_price = 0;
		realGoodsInfo.forEach(function (item, index) {
			if ( offset==index ) {
				var info = {
					recovery_category_name: item.recovery_category_name,
					recovery_category_id: item.recovery_category_id,
					weight: weight,
					unit: item.unit,
					price: item.price,//骑手输入单价
					total_price: parseFloat(item.price*weight).toFixed(2)//该商品的总价
				};
				estimate_price += parseFloat(item.price*weight);
				goods.push(info);
			} else {
				if ( parseFloat(item.total_price)>0 ) estimate_price += parseFloat(item.total_price);
				goods.push(item);
			}
		})
		
		that.setData({
			['form.realGoodsInfo']: goods,
			estimate_price: estimate_price.toFixed(2)
		})
	},
	priceChange: function (e) {
		var that = this;
		var offset = e.currentTarget.dataset.index;
		var realGoodsInfo = that.data.form.realGoodsInfo;
		var goods = [];
		var price = e.detail.value;
		var estimate_price = 0;
		realGoodsInfo.forEach(function (item, index) {
			if ( offset==index ) {
				var info = {
					recovery_category_name: item.recovery_category_name,
					recovery_category_id: item.recovery_category_id,
					weight: item.weight,
					unit: item.unit,
					price: price,//骑手输入单价
					total_price: parseFloat(item.weight*price).toFixed(2)  //该商品的总价
				};
				estimate_price += parseFloat(item.weight*price);
				goods.push(info);
			} else {
				if ( parseFloat(item.total_price)>0 ) estimate_price += parseFloat(item.total_price);
				goods.push(item);
			}
		})
		that.setData({
			['form.realGoodsInfo']: goods,
			estimate_price: estimate_price.toFixed(2)
		})
	},
	addGoods: function (e) {
		var that = this;
		var offset = e.currentTarget.dataset.index;
		var realGoodsInfo = that.data.form.realGoodsInfo;
		var goods = {
			recovery_category_name: '请选择',
			recovery_category_id: 0,
			weight: 0,
			unit: '',
			price: '',
			total_price: 0
		};
		realGoodsInfo.push(goods);
		that.setData({
			['form.realGoodsInfo']: realGoodsInfo
		})
	},
	delGoods: function (e) {
		var that = this;
		var offset = e.currentTarget.dataset.index;
		var realGoodsInfo = that.data.form.realGoodsInfo;
		var goods = [];
		var estimate_price = 0;
		realGoodsInfo.forEach(function (item, index) {
			if ( offset!=index ) {
				estimate_price += (item.total_price*100)/100;
				goods.push(item);
			}
		})
		that.setData({
			['form.realGoodsInfo']: goods,
			estimate_price: estimate_price
		})
	},
	/* 支付方式选择事件 */
	radioChange: function (e) {
		var value = e.detail.value;
		this.setData({
			['form.pay_type']: value
		})
	},
	settleOrderMsgHidden: function () {
		var that = this;
		that.setData({
			settleOrderMsg: true
		})
		/* 使用缓存-记录订单页面tabbar切换到待入库*/
		wx.setStorageSync('order_list_status', 2);
		wx.navigateBack({});
	},
	/* 监听页面息屏*/
	onHide: function () {
		console.log(123);
	},
	/* 回收结算 */
	settleOrder: function (e) {
		wx.showLoading({
			title: '订单结算中...'
		})
		if ( !app.globalData.userInfo ) {
			app.check(e);
			return false;
		}
		var that = this;
		var form = that.data.form;
		var isfalse = false;
		if ( form.realGoodsInfo.length==0 ) {
			wx.hideLoading();
			app.error('请添加回收物品信息');
			return false;
		} else {
			form.realGoodsInfo.forEach(function (item, index) {
				if ( item.recovery_category_name=='' ) {
					wx.hideLoading();
					app.error('物品分类不能为空');
					isfalse = true;
				}
				if ( item.recovery_category_id==0 ) {
					wx.hideLoading();
					app.error('物品分类不能为空');
					isfalse = true;
				}
				if ( !item.weight ) {
					wx.hideLoading();
					app.error('请输入物品重量');
					isfalse = true;
				}
				if ( item.price=='' ) {
					wx.hideLoading();
					app.error('请输入物品单价');
					isfalse = true;
				}
				if ( item.price==0 ) {
					wx.hideLoading();
					app.error('物品单价必须大于0');
					isfalse = true;
				}
			})
			if ( isfalse ) {
				return false;
			}
			if ( form.pay_type=='' ) {
				wx.hideLoading();
				app.error('请选择支付方式');
				return false;
			}
			
			if ( wx.getStorageSync('temp_directory') ) {
				that.uploadRecord(wx.getStorageSync('temp_directory'));
			} else {
				/* 停止录音并上传录音文件 */
				recorderManager.stop();
				setTimeout(function () {
					that.uploadRecord(wx.getStorageSync('temp_directory'));
				},1000)
			}
		}
	},
	
	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {
		wx.removeStorageSync('isRecording');
		wx.removeStorageSync('recordingTime');
	},
	/* 上传录音设备 */
	uploadRecord: function (res) {
		if ( !app.globalData.userInfo ) {
			wx.hideLoading();
			app.error("请登录后再操作");
			return false;
		}
		var that = this;
		var tempFilePath = res.tempFilePath;
		console.log(tempFilePath);
		var formData = app.globalData.config.upload.multipart;
		formData.token = app.globalData.userInfo.token;
		console.log(123);
		console.log(res);
		wx.uploadFile({
			url: app.globalData.config.upload.uploadurl,
			filePath: tempFilePath,
			name: 'file',
			formData: formData,
			success: function (res) {
				console.log(456);
				if ( res.statusCode!=200 ) {
					wx.hideLoading();
					app.error(res.errMsg);
					return false;
				}
				var row = JSON.parse(res.data);
				if ( row.code==1 ) {
					that.setData({
						['form.recordfile']: row.data.url
					})
					var formData = JSON.stringify(that.data.form);
					app.request('/api/timetable.user/settleOrder', { data: formData }, function (data, ret) {
							wx.removeStorageSync('isRecording');
							wx.removeStorageSync('recordingTime');
							clearTimeout(recordingTimeInterval);
							clearInterval(scopeRecordInterval);
							if ( data.pay_type==0 ) {
								//余额支付或已支付过
								that.setData({
									settleOrderMsg: false
								})
								wx.removeStorageSync('temp_directory');
							} else {
								//发起支付
								wx.requestPayment({
									'timeStamp': data.payData.timeStamp,
									'nonceStr': data.payData.nonceStr,
									'package': data.payData.package,
									'signType': data.payData.signType,
									'paySign': data.payData.paySign,
									'success': function (res) {
										if ( res.errMsg=='requestPayment:ok' ) {
											wx.hideLoading();
											that.setData({
												settleOrderMsg: false
											})
											wx.removeStorageSync('temp_directory');
										} else {
											wx.hideLoading();
											app.error("支付失败请重新结算");
										}
									},
									'fail': function (res) {
										wx.hideLoading();
										app.error("支付失败请重新结算");
									}
								});
							}
						}, function (data, ret) {
							wx.hideLoading();
							app.error(ret.msg);
							return false;
						}
					);
				}
			}, fail: function (res) {
				wx.hideLoading();
				console.log(res);
				app.error("录音上传未成功");
				return false;
			}
		});
	},
	bindback: function () {
		if ( wx.getStorageSync('isRecording')==true ) {
			app.error("请先完成订单结算");
			return false;
		}
		wx.navigateBack();
	}
})